package com.agent.crm.base;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.agent.crm.config.AppConfig;
import com.agent.crm.imagecache.ImageFactory;
import com.agent.crm.imagecache.ImageTask;
import com.agent.crm.imagecache.ImageTaskExecutor;

public abstract class BaseActivity extends Activity implements OnClickListener{

	
	protected abstract int initLayout();
	
	protected abstract View initCustomLayout();
	
	protected abstract void initViewCmp();
	
	protected abstract void initListener();
	
	protected abstract void initData();
	
	protected abstract void initAsycnData();
	
	protected abstract void changeDefaultSetting();
	
	/** 屏幕参数 */
	public DisplayMetrics mDisplayMetrics = null;
	
	/** 图片加载工厂 */
	protected ImageFactory mImageFactory = null;
	
	/** 异步图片加载线程管理类 */
	protected ImageTaskExecutor mTaskExecutor = null;
	
	/** 网络请求加载dialog */
	protected ProgressDialog mLoadingDialog = null;

	/** 系统提示框对象 */
	protected AlertDialog mSimpleAlertDialog = null;

	/** 自定dialog对象 */
	protected AlertDialog mCustomAlertDialog = null;
	
	/** activity 是否处于可见状态 */
	protected boolean mIsActive = false;

	private List<Activity> activityStack = new LinkedList<Activity>();
	
	public boolean customLayoutFlag=false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		changeDefaultSetting();
		if (!AppConfig.isDebug) {
			// 程序异常统一处理机制
			errorProcess();
		}
		// 判断是否要acitivity 标题栏 true 为不要Title ，false 为要他title栏。默认true不要Title栏。
		if (AppConfig.isNoActivityTitle) {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
		// 判断是否全屏 true为全屏 false为不全屏
		if (AppConfig.isFullScreen) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
		/** 初始化设备屏幕参数 */
		mDisplayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
		// 初始化图片加载工厂
		mImageFactory = new ImageFactory();
		// 初始化图片加载异步线程管理对象
		mTaskExecutor = new ImageTaskExecutor();
		if(customLayoutFlag){
			setContentView(initCustomLayout());
		}else{
			setContentView(initLayout());
		}
		initViewCmp();
		initListener();
		addToStack(this);
	}
	
	
	private boolean addToStack(Activity activity){
		if(activityStack.contains(activity)){
			int location=activityStack.indexOf(activity);
			activityStack.remove(location);
			activityStack.add(activity);
		}else{
			if(!activityStack.add(activity)){
				return false;
			};
		}
		return true;
	}
	
	/**
	 * 处理程序崩溃跳转到默认的Activity
	 */
	private final void errorProcess() {
		Thread.currentThread().setUncaughtExceptionHandler(
				new UncaughtExceptionHandler() {
					@Override
					public void uncaughtException(Thread thread, Throwable ex) {
//						LogPrinter.debugError("崩溃时间:"
//								+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//										.format(System.currentTimeMillis()));
//						LogPrinter.debugError("崩溃简短信息:" + ex.getMessage());
//						LogPrinter.debugError("崩溃线程名称:" + thread.getName()
//								+ "崩溃线程ID:" + thread.getId());
//
//						ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//						PrintWriter pw = new PrintWriter(outStream);
//						ex.printStackTrace(pw);
//
//						Intent intent = new Intent();
//						intent.putExtra(AbsInitApplication.ERROR_INFO,
//								outStream.toString());
//						intent.setClass(BaseActivity.this,
//								AbsInitApplication.errorProcessActivity);
//						BaseActivity.this.startActivity(intent);
						
						exitApp();
						
					}
				});
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mImageFactory.recycleBitmaps();
		mImageFactory = null;
		// 将当前acitivity移除activity管理集合中
		//ActivityManagerTool.getActivityManager().removeActivity(this);
		System.gc();
		activityStack.remove(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mIsActive = true;
		initAsycnData();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		mIsActive = true;
		if(null==mTaskExecutor){
			mTaskExecutor = new ImageTaskExecutor();
		}
		initData();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mIsActive = false;
		dismissLoadingDialog();
		dismissSimpleAlertDialog();
		dismissCustomAlertDialog();
		mTaskExecutor.terminateTaskThread();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// 先判断是否是返回键
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 判断是不是首页
			if (this.getClass() != AppConfig.mainView) {
				// 如果不是首页但是底部导航则执行跳转到首页操作
				return super.onKeyDown(keyCode, event);
			} else {
				// 首页按返回键提示是否退出
				 //showExitDialog();
				AppConfig.BackKeyCount++;
				if (AppConfig.BackKeyCount >= 2) {
					exitApp();
				} else {
					//Toast.makeText(this, "在按一次退出程序", Toast.LENGTH_SHORT).show();
					new Thread(new Runnable() {
						@Override
						public void run() {
							Timer timer = new Timer();
							timer.schedule(new MyTask(), 10000);
						}
					}).start();
				}
			}
		}
		return false;
	}
	
	/**
	 *  退出程序操作
	 */
	public void exitApp() {
		for (Activity activity : activityStack) {
			if(activity!=null){
			   activity.finish();
			}
		}
		android.os.Process.killProcess(android.os.Process.myPid());
		finish();
		System.exit(0);
	}
	
	/**
	 * 为ImageView组件填充 Bitmap
	 * 
	 * @param imgUrl
	 *            图片对应的下载地址
	 * @param view
	 *            图片要显示的view对象
	 * @param error_bg_Id
	 *            当无法下载图片时显示的背景图
	 * @param isSaveImage
	 *            是否保存图片，true 为保存，false为不保存
	 * @param SaveImagepath
	 *            保存图片的路径
	 */
	public void inflateImage(final String imgUrl, final View view,
			final int error_bg_Id, final boolean isSaveImage,
			final String SaveImagepath) {

		try {
			view.setTag(imgUrl);
			Bitmap bmp = mImageFactory.getCachedImage(imgUrl);
			if (bmp != null) {
				((ImageView) view)
						.setBackgroundDrawable(new BitmapDrawable(bmp));
				return;
			} else {
				((ImageView) view).setImageBitmap(null);
				mTaskExecutor.addNewTask(new ImageTask(imgUrl) {

					Bitmap bmp = null;
					Handler inflateHandler = new Handler() {
						public void handleMessage(Message msg) {
							if (view != null && view instanceof ImageView) {
								if (imgUrl.equals(view.getTag())) {
									if (bmp == null) {
										bmp = BitmapFactory.decodeResource(getResources(), error_bg_Id);
									}
									((ImageView) view)
											.setBackgroundDrawable(new BitmapDrawable(
													bmp));
								}
							}
						}
					};

					@Override
					public void execute() {
						bmp = mImageFactory.getAsynchronousImage(imgUrl,
								isSaveImage, SaveImagepath);
						inflateHandler.sendMessage(new Message());
					}
				});
			}

		} catch (Exception e) {
			Log.d("Error","Error --> BaseActivity.inflateImage(): e = "
					+ e.toString());
		}
	}
	
	/**
	 * 开启加载对话框
	 * 
	 * @param msg
	 *            需要显示的提示文本信息
	 */
	public void showLoadingDialog(String msg) {
		Log.d("Activity","showLoadingDialog  mIsActive = " + mIsActive);
		if (!mIsActive) {
			return;
		}
		if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
			return;
		}
		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setMessage(msg);
		// mLoadingDialog.setOnKeyListener(mOnKeyListener);
		mLoadingDialog.setCancelable(false);
		mLoadingDialog.show();
	}
	
	/**
	 * 开启加载对话框
	 * 
	 * @param title
	 *            加载对话框标题名称
	 * @param msg
	 *            需要显示的提示文本信息
	 */
	public void showLoadingDialog(String title, String msg) {
		Log.d("Activity","showLoadingDialog  mIsActive = " + mIsActive);
		if (!mIsActive) {
			return;
		}
		if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
			return;
		}
		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setTitle(title);
		mLoadingDialog.setMessage(msg);
		mLoadingDialog.setOnKeyListener(mOnKeyListener);
		mLoadingDialog.show();
	}
	
	private OnKeyListener mOnKeyListener = new OnKeyListener() {

		@Override
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK
					&& event.getAction() == KeyEvent.ACTION_DOWN) {
				if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
					dismissLoadingDialog();
				}
				/**
				 * 下载线程存在的话，须停止下载线程
				 */
			}
			return true;
		}
	};
	
	/**
	 * 开启SimpleAlertDialog
	 * 
	 * @param msg
	 *            需要显示的文本信息
	 * 
	 */
	public void showSimpleAlertDialog(String msg) {
		if (!mIsActive) {
			return;
		}
//		int sure = this.getResources().getIdentifier("sure", "string", this.getPackageName());
		mSimpleAlertDialog = new AlertDialog.Builder(this)
		.setMessage(msg)
		.setPositiveButton("确定", null).create();
		mSimpleAlertDialog.show();
	}
	
	/**
	 * 开启SimpleAlertDialog
	 * 
	 * @param title
	 *            需要显示的文本标题
	 * @param msg
	 *            需要显示的文本信息
	 * 
	 */
	public void showSimpleAlertDialog(String title, String msg) {
		if (!mIsActive) {
			return;
		}
		mSimpleAlertDialog = new AlertDialog.Builder(this).setTitle(title)
				.setMessage(msg).setPositiveButton("确定", null).create();
		mSimpleAlertDialog.show();
	}
	
	/**
	 * 开启SimpleAlertDialog
	 * 
	 * @param title
	 *            需要显示的文本标题
	 * @param msg
	 *            需要显示的文本信息
	 * @param btnName
	 *            确定按钮上的文本信息
	 * 
	 */
	public void showSimpleAlertDialog(String title, String msg, String btnName) {
		if (!mIsActive) {
			return;
		}
		mSimpleAlertDialog = new AlertDialog.Builder(this).setTitle(title)
				.setMessage(msg).setPositiveButton(btnName, null).create();
		mSimpleAlertDialog.show();
	}
	
	/**
	 * 取消加载对话框
	 */
	public void dismissLoadingDialog() {
		if (mLoadingDialog != null) {
			mLoadingDialog.dismiss();
		}
	}
	
	/**
	 * 关闭mSimpleAlertDialog
	 */
	public void dismissSimpleAlertDialog() {
		if (mSimpleAlertDialog != null) {
			mSimpleAlertDialog.dismiss();
		}
	}
	
	/**
	 * 关闭mCustomAlertDialog
	 */
	public void dismissCustomAlertDialog() {
		if (mCustomAlertDialog != null) {
			mCustomAlertDialog.dismiss();
		}
	}
	
	class MyTask extends TimerTask {

		@Override
		public void run() {
			AppConfig.BackKeyCount = 0;
		}

	}
	
}
